package com.ihr360.job.core.repository.dao;

import com.ihr360.job.core.entity.JobExecution;
import com.ihr360.job.core.entity.JobInstance;
import com.ihr360.job.core.repository.PageData;

import java.util.List;
import java.util.Set;

/**
 * Data Access Object for job executions.
 *
 * @author Lucas Ward
 * @author Robert Kasanicky
 */
public interface JobExecutionDao {

    /**
     * Save a new JobExecution.
     * <p>
     * Preconditions: jobInstance the jobExecution belongs to must have a
     * jobInstanceId.
     *
     * @param jobExecution
     */
    void saveJobExecution(JobExecution jobExecution);

    /**
     * Update and existing JobExecution.
     * <p>
     * Preconditions: jobExecution must have an Id (which can be obtained by the
     * save method) and a jobInstanceId.
     *
     * @param jobExecution
     */
    void updateJobExecution(JobExecution jobExecution);

    /**
     * @param page start from 1
     * Return all {@link JobExecution} job executions sorted
     * backwards by creation order (so the first element is the most recent).
     */
    PageData<JobExecution> findJobExecutions(int page,int size);

    PageData<JobExecution> findFailedJobExecutions(int page,int size);

    PageData<JobExecution> findUnExcepedJobExecutions(int page,int size);

    PageData<JobExecution> findLongTimeJobExecutions(int page,int size,int minutes);

    /**
     * 强制将执行时间超过多长时间的任务执行停止操作
     * @param interval
     * @return
     */
    int abandonJobExecutedTimeLt(int interval);

    /**
     * Return all {@link JobExecution} for given {@link JobInstance}, sorted
     * backwards by creation order (so the first element is the most recent).
     */
    List<JobExecution> findJobExecutions(JobInstance jobInstance);

    /**
     * Find the last {@link JobExecution} to have been created for a given
     * {@link JobInstance}.
     *
     * @param jobInstance the {@link JobInstance}
     * @return the last {@link JobExecution} to execute for this instance
     */
    JobExecution getLastJobExecution(JobInstance jobInstance);

    /**
     * @return all {@link JobExecution} that are still running (or indeterminate
     * state), i.e. having null end date, for the specified job name.
     */
    Set<JobExecution> findRunningJobExecutions(String jobName);

    /**
     * @return the {@link JobExecution} for given identifier.
     */
    JobExecution getJobExecution(Long executionId);

    /**
     * Because it may be possible that the status of a JobExecution is updated
     * while running, the following method will synchronize only the status and
     * version fields.
     *
     * @param jobExecution to be updated.
     */
    void synchronizeStatus(JobExecution jobExecution);

}
